/*
 * index.c
 *
 *  Created on: Jul 2, 2009
 *      Author: jacky
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "core.h"

/*
 * cgi 主程序
 */
int cgiMain()
{
	HttpRequest request;
	HttpResponse response;
	CoreStatus reqStatus;
	CoreStatus rspStatus;
	ActionStatus actionStatus;
	reqStatus = initRequest(&request, controllers, controllersLength);
	rspStatus = initResponse(&response);

	if (reqStatus == CORE_OK && rspStatus == CORE_OK)
	{
		actionStatus = (request.curAction->action)(&request, &response);
		if (ActionOK == actionStatus)
		{
			/* auto render view */
			if (response.autoRender)
			{
				render(&request, &response);
			}
		}
		else
		{
			/* TODO:Jacky Action执行异常的捕捉 */
			switch (actionStatus) {
				case ActionFAIL:

					break;
				default:
					break;
			}
		}

		destoryResponse(&response);
		destoryRequest(&request);

	}
	else
	{
		/* TODO:Jacky initRequest or initRespones error */
		switch (reqStatus)
		{
		case CORE_ERROR_CTLID:
			cgiError("initialize Request error:ERROR_CTLID");
			break;
		case CORE_ERROR_ACTID:
			cgiError("initialize Request error:ERROR_ACTID");
			break;
		default:
			break;
		}
	}
	/* release resources */
#ifdef DEBUG

	struct timeval diff = elapsed_time();
	printf("<!-- debug info %ld.%06ld seconds, "
		"ctrl={id=%d; name=\"%s\"}, "
		"action={id=%d; name=\"%s\"} -->\n", diff.tv_sec,diff.tv_usec, request.ctrlid,
			request.curCtrl ? request.curCtrl->name : "", request.actionid,
			request.curAction ? request.curAction->name : "");
#endif /* DEBUG */
	return 0/* OK */;
}

